package org.twndmv.web;

import java.io.IOException;
import java.security.acl.LastOwnerException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twndmv.bo.Color;
import org.twndmv.bo.Sex;
import org.twndmv.bo.State;
import org.twndmv.dto.PersonDTO;
import org.twndmv.dto.PhysicalDetailsDTO;
import org.twndmv.dto.ResidenceDTO;
import org.twndmv.dto.VehicleRegistrationDTO;
import org.twndmv.ejb.DmvTestUtilRemote;
import org.twndmv.ejb.DriverMgmtRemote;
import org.twndmv.ejb.PersonMgmtRemote;
import org.twndmv.ejb.VehicleMgmtRemote;

public class DmvController extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final Log log = LogFactory.getLog(DmvController.class);
    private static final String UNKNOWN_COMMAND_URL = 
        "/WEB-INF/dmv/UnknownCommand.jsp";
    protected static final String DISPLAY_EXCEPTION_URL = 
            "/WEB-INF/dmv/DisplayException.jsp";
    protected static final String DISPLAY_RESULT_URL = 
            "/WEB-INF/dmv/DisplayResult.jsp";
    public static final String ADMIN_TYPE = "admin";
    public static final String ANONYMOUS_TYPE = "anonymous";
    public static final String PING_COMMAND = "Ping";
    public static final String EXCEPTION_PARAM = "exception";
    public static final String COMMAND_PARAM = "command";
    public static final String HANDLER_TYPE_KEY = "type";

    protected static final String RESULT_PARAM = "result";
    
    //commands
    public static final String CREATE_DRIVER_COMMAND = "Create Driver";
    public static final String CREATE_REGISTRATION_COMMAND = "Create Registration";
    public static final String GET_ALL_DRIVERS_COMMAND = "Get All Drivers";
    public static final String GET_DRIVER_COMMAND = "Get Driver";
    public static final String CHANGE_ADDRESS_COMMAND = "Change Address";
    public static final String GET_ALL_REGISTRATIONS_COMMAND = "Get All Registrations";
    public static final String GET_REGISTRATION_COMMAND = "Get Registration";
    public static final String GET_DRIVERS_BY_LAST_NAME_COMMAND = "Get Drivers By Last Name";
    public static final String GET_REGISTRATIONS_BY_OWNER_COMMAND = "Get Registrations By Owner";
    public static final String GET_REGISTRATIONS_BY_MAKE_MODEL_COMMAND = "Get Registrations By Make Model";
    public static final String RETRIEVE_DRIVERS_COMMAND = "Retrieve Drivers";
    public static final String RETRIEVE_REGISTRATIONS_COMMAND = "Retrieve Registrations";
    public static final String POPULATE_DB_COMMAND = "Populate DB";
    public static final String RESET_DB_COMMAND = "Reset DB";

    private Map<String, GetHandler> getHandlers = new HashMap<String, GetHandler>();
    private Map<String, PostHandler> postHandlers = new HashMap<String, PostHandler>();
	
    @EJB
    protected DriverMgmtRemote driverManager;
    @EJB
    protected PersonMgmtRemote personManager;
    @EJB
    protected VehicleMgmtRemote carManager;
    @EJB
    protected DmvTestUtilRemote testUtil;
	
    public void init() throws ServletException {
        log.debug("init() called ");
        try {
            ServletConfig config = getServletConfig();
            initEJBs(config);
            
            //build a list of handlers for individual commands
            //String handlerType = config.getInitParameter(HANDLER_TYPE_KEY);
            getHandlers.put(GET_ALL_DRIVERS_COMMAND, new GetAllDrivers()); 
            getHandlers.put(GET_DRIVER_COMMAND, new GetDriver());
            getHandlers.put(RETRIEVE_DRIVERS_COMMAND, new RetrieveDrivers());
            getHandlers.put(RETRIEVE_REGISTRATIONS_COMMAND, new RetrieveRegistrations());
            getHandlers.put(GET_ALL_REGISTRATIONS_COMMAND, new GetAllRegistrations());
            getHandlers.put(GET_REGISTRATION_COMMAND, new GetRegistration());
            getHandlers.put(GET_REGISTRATIONS_BY_OWNER_COMMAND, new GetRegistrationsByOwner());
            getHandlers.put(GET_REGISTRATIONS_BY_MAKE_MODEL_COMMAND, new GetRegistrationsByMakeModel());
            getHandlers.put(CREATE_DRIVER_COMMAND, new CreateDriver());
            getHandlers.put(CREATE_REGISTRATION_COMMAND, new CreateRegistration());
            getHandlers.put(GET_DRIVERS_BY_LAST_NAME_COMMAND, new GetDriversByLastName());
            getHandlers.put(CHANGE_ADDRESS_COMMAND, new ChangeAddr());
            getHandlers.put(POPULATE_DB_COMMAND, new PopulateDB());
            getHandlers.put(RESET_DB_COMMAND, new ResetDB());
            
            postHandlers.put(CREATE_DRIVER_COMMAND, new CreateDriverPost());
            postHandlers.put(CREATE_REGISTRATION_COMMAND, new CreateRegistrationPost());
            postHandlers.put(CHANGE_ADDRESS_COMMAND, new ChangeAddrPost());
            
           
            //log.debug("configured handler type:" + handlerType +
            //        " with " + handlers);
        }
        catch (Exception ex) {
            log.fatal("error initializing GetHandler", ex);
            throw new ServletException("error initializing GetHandler", ex);
        }
    }

    private void initEJBs(ServletConfig config) throws Exception {
        log.debug("initEJBs()");
      //build an InitialContext from Servlet.init properties in web.xml
        InitialContext jndi = null;
        String ctxFactory = config.getServletContext()
                                  .getInitParameter(Context.INITIAL_CONTEXT_FACTORY);
        log.debug(Context.INITIAL_CONTEXT_FACTORY + "=" + ctxFactory);
        if (ctxFactory!=null) {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory);
                jndi = new InitialContext(env);
        }
        else {
                jndi = new InitialContext();
        }
        if (driverManager == null) {   
            String jndiName = config.getServletContext().getInitParameter("driver.remote");
            driverManager = (DriverMgmtRemote)jndi.lookup(jndiName);
            log.debug("driverManager initialized:" + driverManager);
        }        
        if(personManager == null) {	
            String jndiName = config.getServletContext().getInitParameter("person.remote");
            personManager = (PersonMgmtRemote)jndi.lookup(jndiName);
            log.debug("personManager initialized:" + personManager);
        }
        if(carManager == null) {    	
            String jndiName = config.getServletContext().getInitParameter("vehicle.remote");
            carManager = (VehicleMgmtRemote)jndi.lookup(jndiName);
            log.debug("carManager initialized:" + carManager);
            
        }
        if(testUtil == null) {
        	String jndiName = config.getServletContext().getInitParameter("testutil.remote");
        	 testUtil = (DmvTestUtilRemote)jndi.lookup(jndiName);
             log.debug("testUtil initialized:" + testUtil);
        }
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException {
        log.debug("doGet() called");
        String command = request.getParameter(COMMAND_PARAM);
        log.debug("command=" + command);
        try {
            if (command != null) {
                GetHandler handler = getHandlers.get(command);
                if (handler != null) {
                    handler.handle(request, response);
                }
                else {
                    RequestDispatcher rd = 
                        getServletContext().getRequestDispatcher(
                            UNKNOWN_COMMAND_URL);
                            rd.forward(request, response);
                }
            }
            else {
                throw new Exception("no " + COMMAND_PARAM + " supplied"); 
            }
        }
        catch (Exception ex) {
            log.error("error within GET", ex);
            request.setAttribute(EXCEPTION_PARAM, ex);
            RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    UNKNOWN_COMMAND_URL);
                    rd.forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException {
        log.debug("doPost() called");
        String command = request.getParameter(COMMAND_PARAM);
        log.debug("command=" + command);
        try {
            if (command != null) {
                PostHandler handler = postHandlers.get(command);
                if (handler != null) {
                    handler.handle(request, response);
                }
                else {
                	log.debug("No post handler, calling doGet() instead");
                    doGet(request,response);
                }
            }
            else {
                throw new Exception("no " + COMMAND_PARAM + " supplied"); 
            }
        }
        catch (Exception ex) {
            log.error("error within POST", ex);
            request.setAttribute(EXCEPTION_PARAM, ex);
            RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    UNKNOWN_COMMAND_URL);
                    rd.forward(request, response);
        }
      
    }

    public void destroy() {
        log.debug("destroy() called");
    }
    
    private abstract class PostHandler {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	protected static final String ID_PARAM = "id";
        protected static final String FIRST_NAME_PARAM = "firstName";
        protected static final String MIDDLE_NAME_PARAM = "middleName";
        protected static final String LAST_NAME_PARAM = "lastName";
    	protected static final String HEIGHT_PARAM = "height";
        protected static final String WEIGHT_PARAM = "weight";
        protected static final String HAIR_COLOR_PARAM = "hairColor";
        protected static final String EYE_COLOR_PARAM = "eyeColor";
        protected static final String STREET_NO_PARAM = "streetNo";
        protected static final String STREET_NAME_PARAM = "streetName";
        protected static final String CITY_PARAM = "city";
        protected static final String STATE_PARAM = "state";
        protected static final String ZIP_PARAM = "zipCode";
        protected static final String GENDER_PARAM = "gender";
        protected static final String DOB_PARAM = "dateOfBirth";
        protected static final String MOVE_IN_PARAM = "moveInDate";
        protected static final String MOVE_OUT_PARAM = "moveOutDate";
        
        protected static final String MAKE_PARAM = "make";
        protected static final String MODEL_PARAM = "model";
        protected static final String CAR_YEAR_PARAM = "carYear";
        protected static final String CAR_COLOR_PARAM = "carColor";
        protected static final String TAG_NO_PARAM = "tagNo";
        protected static final String VIN_PARAM = "vin";
        protected static final String EXPR_DATE_PARAM = "expirationDate";
        
        
        
        protected static final String CREATE_DRIVER_URL = 
                "/WEB-INF/dmv/CreateDriver.jsp";
        
        protected String action;
        public void handle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException {
            try {
                doHandle(request, response);
            }
            catch (Exception ex) {
                log.error("error in " + action, ex);
                request.setAttribute(EXCEPTION_PARAM, ex);                
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
        
        public abstract void doHandle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException, Exception;
    }
    
    private abstract class GetHandler {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
        protected static final String ID_PARAM = "id";
        protected static final String INDEX_PARAM = "index";
        protected static final String COUNT_PARAM = "count";
        protected static final String RESULT_PARAM = "result";
        protected static final String EXCEPTION_PARAM = "exception";
        protected static final String NEXT_INDEX_PARAM = "nextIndex";
        protected static final String LAST_NAME_PARAM = "lastName";
        protected static final String MAKE_PARAM = "make";
        protected static final String MODEL_PARAM = "model";
        protected static final String OWNER_ID_PARAM = "ownerId";
        
        protected static final String SAMPLES_PARAM = "sampleIds";
        
        protected static final String DISPLAY_REGISTRATIONS_URL = 
            "/WEB-INF/dmv/DisplayRegistrations.jsp";
        protected static final String DISPLAY_REGISTRATION_URL = 
            "/WEB-INF/dmv/DisplayRegistration.jsp";
        protected static final String DISPLAY_DRIVERS_URL = 
            "/WEB-INF/dmv/DisplayDrivers.jsp";
        protected static final String DISPLAY_DRIVER_URL = 
            "/WEB-INF/dmv/DisplayDriver.jsp";
        protected static final String CREATE_DRIVER_URL = 
                "/WEB-INF/dmv/CreateDriver.jsp";
        protected static final String CREATE_REGISTRATION_URL = 
                "/WEB-INF/dmv/CreateRegistration.jsp";
        protected static final String RETRIEVE_REGISTRATION_URL = 
                "/WEB-INF/dmv/RetrieveRegistrations.jsp";
        protected static final String RETRIEVE_DRIVER_URL = 
                "/WEB-INF/dmv/RetrieveDrivers.jsp";
        protected static final String CHANGE_ADDR_URL = 
                "/WEB-INF/dmv/ChangeAddr.jsp";
        
        protected String action;
        public void handle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException {
            try {
                doHandle(request, response);
            }
            catch (Exception ex) {
                log.error("error in " + action, ex);
                request.setAttribute(EXCEPTION_PARAM, ex);                
                RequestDispatcher rd = getServletContext().getRequestDispatcher(
                    DISPLAY_EXCEPTION_URL);
                rd.forward(request, response);
            }
        }
        
        public abstract void doHandle(HttpServletRequest request, 
                HttpServletResponse response) 
                throws ServletException, IOException, Exception;
    }
    
    private class GetAllDrivers extends GetHandler {

    	/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.getAllDrivers"; //describe action in case of exception
            
            String indexStr = (String)request.getParameter(INDEX_PARAM);
            String countStr = (String)request.getParameter(COUNT_PARAM);
            int index = Integer.parseInt(indexStr);
            int count = Integer.parseInt(countStr);
            
            List<PersonDTO> people = driverManager.getAllDrivers();
            List<PersonDTO> results = new ArrayList<PersonDTO>();
            
            
            for(int i = index; i < index + count; i++) {
            	try{
            		PersonDTO newPeep = people.get(i);

                	results.add(newPeep);
            	} catch(IndexOutOfBoundsException aoe) {
            		log.debug("Reached the end of the list.");
            		break;
            	}
            }
            int nextIndex = (results.size()==0) ?
                index : index + results.size();
            count = (results.size() >= count) ? count : results.size();
            //request.setAttribute(RESULT_PARAM, people);
            request.setAttribute(RESULT_PARAM, results);
            request.setAttribute(INDEX_PARAM, index);
            request.setAttribute(COUNT_PARAM, count);
            request.setAttribute(NEXT_INDEX_PARAM, nextIndex);

            //RequestDispatcher rd =
            //  getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            RequestDispatcher rd =
              getServletContext().getRequestDispatcher(DISPLAY_DRIVERS_URL);
            rd.forward(request, response);

    	}

    }
    
    private class CreateDriver extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		
    		List<String> colors = new ArrayList<String>();
    		for(Color c : Color.values()) {
    			colors.add(c.getName());
    		}    		
    		List<String> states = new ArrayList<String>();
    		for(State c : State.values()) {
    			states.add(c.getName());
    		}
    		
    		request.setAttribute("colors", colors);
    		request.setAttribute("states", states);
    		
    		RequestDispatcher rd =
    	              getServletContext().getRequestDispatcher(CREATE_DRIVER_URL);
    	            rd.forward(request, response);
    	}

    }
    
    private class CreateDriverPost extends PostHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		DateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy");
    		
    		PersonDTO newPerson = new PersonDTO();
    		PhysicalDetailsDTO physicalDetails = new PhysicalDetailsDTO();
    		String height = (String)request.getParameter(HEIGHT_PARAM);
    		String weight = (String)request.getParameter(WEIGHT_PARAM);
    		String eyeColor = (String)request.getParameter(EYE_COLOR_PARAM);
    		String hairColor = (String)request.getParameter(HAIR_COLOR_PARAM);
    		
    		physicalDetails.setHeight(Integer.parseInt(height));
    		physicalDetails.setWeight(Integer.parseInt(weight));
    		physicalDetails.setEyeColor(Color.translate(eyeColor));
    		physicalDetails.setHairColor(Color.translate(hairColor));
    		physicalDetails.setSEX(Sex.translate(request.getParameter(GENDER_PARAM)));
    		physicalDetails.setDob(dateParser.parse(request.getParameter(DOB_PARAM)));
    		newPerson.setPhysicalDetails(physicalDetails);
    		
    		newPerson.setFirstName(request.getParameter(FIRST_NAME_PARAM));
    		newPerson.setMiddleName(request.getParameter(MIDDLE_NAME_PARAM));
    		newPerson.setLastName(request.getParameter(LAST_NAME_PARAM));
    		
    		ResidenceDTO newRes = new ResidenceDTO();
    		newRes.setStreetNo(Integer.parseInt(request.getParameter(STREET_NO_PARAM)));
    		newRes.setStreetName(request.getParameter(STREET_NAME_PARAM));
    		newRes.setCity(request.getParameter(CITY_PARAM));
    		newRes.setState(State.translate((request.getParameter(STATE_PARAM))));
    		newRes.setZipCode(Integer.parseInt(request.getParameter(ZIP_PARAM)));
    		newRes.setMoveIn(dateParser.parse(request.getParameter(MOVE_IN_PARAM)));
    		newRes.setMoveOut(dateParser.parse(request.getParameter(MOVE_OUT_PARAM)));
    		newPerson.getResidences().add(newRes);
    		
    		driverManager.addDriver(newPerson);
    		String result = "Driver added successfully...";

            request.setAttribute(RESULT_PARAM, result);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            rd.forward(request, response);
    		
    	}

    }
    
    private class RetrieveRegistrations extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		
    		List<PersonDTO> people = driverManager.getAllDrivers();
    		List<PersonDTO> samples = new ArrayList<PersonDTO>();
    		int num = (people.size() >= 10 ) ? 10 : people.size();
    		for(int i = 0; i < num; i++) {
    			samples.add(people.get(i));
    		}
    		
    		
    		List<String> makes = new ArrayList<String>();
    		List<String> models = new ArrayList<String>();
    		List<VehicleRegistrationDTO> cars = carManager.getAllVehicles();
    		
    		for(VehicleRegistrationDTO car : cars) {
    			if(!makes.contains(car.getMake())) {
    				makes.add(car.getMake());
    			}
    			if(!models.contains(car.getModel())) {
    				models.add(car.getModel());
    			}
    		}
    		
    		request.setAttribute(MODEL_PARAM, models);
    		request.setAttribute(MAKE_PARAM, makes);
    		request.setAttribute(SAMPLES_PARAM, samples);
    		
    		RequestDispatcher rd =
    	              getServletContext().getRequestDispatcher(RETRIEVE_REGISTRATION_URL);
    	            rd.forward(request, response);
    	}

    }
    
    private class RetrieveDrivers extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		
    		List<PersonDTO> people = driverManager.getAllDrivers();
    		List<PersonDTO> samples = new ArrayList<PersonDTO>();
    		int num = (people.size() >= 10 ) ? 10 : people.size();
    		for(int i = 0; i < num; i++) {
    			samples.add(people.get(i));
    		}
    		
    		request.setAttribute(SAMPLES_PARAM, samples);
    		
    		RequestDispatcher rd =
    	              getServletContext().getRequestDispatcher(RETRIEVE_DRIVER_URL);
    	            rd.forward(request, response);
    	}

    }
    
    private class CreateRegistration extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		RequestDispatcher rd =
    	              getServletContext().getRequestDispatcher(CREATE_REGISTRATION_URL);
    	            rd.forward(request, response);
    	}

    }
    
    private class ChangeAddrPost extends PostHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		DateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy");
    		
    		ResidenceDTO newRes = new ResidenceDTO();
    		newRes.setStreetNo(Integer.parseInt(request.getParameter(STREET_NO_PARAM)));
    		newRes.setStreetName(request.getParameter(STREET_NAME_PARAM));
    		newRes.setCity(request.getParameter(CITY_PARAM));
    		newRes.setState(State.translate((request.getParameter(STATE_PARAM))));
    		newRes.setZipCode(Integer.parseInt(request.getParameter(ZIP_PARAM)));
    		newRes.setMoveIn(dateParser.parse(request.getParameter(MOVE_IN_PARAM)));
    		newRes.setMoveOut(dateParser.parse(request.getParameter(MOVE_OUT_PARAM)));
    		
    		driverManager.moveResidence(Long.parseLong(request.getParameter(ID_PARAM)), newRes);
    		String result = "Address changed successfully...";

            request.setAttribute(RESULT_PARAM, result);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            rd.forward(request, response);
    		
    	}

    }
    
    private class ChangeAddr extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		
    		List<PersonDTO> people = driverManager.getAllDrivers();
    		List<PersonDTO> samples = new ArrayList<PersonDTO>();
    		int num = (people.size() >= 10 ) ? 10 : people.size();
    		for(int i = 0; i < num; i++) {
    			samples.add(people.get(i));
    		}
    		
    		request.setAttribute(SAMPLES_PARAM, samples);
    		
    		RequestDispatcher rd =
    	              getServletContext().getRequestDispatcher(CHANGE_ADDR_URL);
    	            rd.forward(request, response);
    	}

    }
    
    private class CreateRegistrationPost extends PostHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		DateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy");
    		
    		VehicleRegistrationDTO newCar = new VehicleRegistrationDTO();
    		
    		newCar.setColor(Color.translate(request.getParameter(CAR_COLOR_PARAM)));
    		newCar.setExpiration(dateParser.parse(request.getParameter(EXPR_DATE_PARAM)));
    		newCar.setMake(request.getParameter(MAKE_PARAM));
    		newCar.setModel(request.getParameter(MODEL_PARAM));
    		newCar.setTagNo(request.getParameter(TAG_NO_PARAM));
    		newCar.setVin(request.getParameter(VIN_PARAM));
    		newCar.setYear(Integer.parseInt(request.getParameter(CAR_YEAR_PARAM)));
    		
    		carManager.addRegistration(newCar);
    		String result = "Registration added successfully...";

            request.setAttribute(RESULT_PARAM, result);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            rd.forward(request, response);
    		
    	}

    }
    
    private class GetAllRegistrations extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
action = "EJB.getAllRegistrations"; //describe action in case of exception
            
            String indexStr = (String)request.getParameter(INDEX_PARAM);
            String countStr = (String)request.getParameter(COUNT_PARAM);
            int index = Integer.parseInt(indexStr);
            int count = Integer.parseInt(countStr);
            
            List<VehicleRegistrationDTO> cars = carManager.getAllVehicles();
            List<VehicleRegistrationDTO> results = new ArrayList<VehicleRegistrationDTO>();
            
            
            for(int i = index; i < index + count; i++) {
            	try{
            		VehicleRegistrationDTO newPeep = cars.get(i);

                	results.add(newPeep);
            	} catch(IndexOutOfBoundsException aoe) {
            		log.debug("Reached the end of the list.");
            		break;
            	}
            }
            int nextIndex = (results.size()==0) ?
                index : index + results.size();
            //request.setAttribute(RESULT_PARAM, people);
            request.setAttribute(RESULT_PARAM, results);
            request.setAttribute(INDEX_PARAM, index);
            request.setAttribute(COUNT_PARAM, count);
            request.setAttribute(NEXT_INDEX_PARAM, nextIndex);

            //RequestDispatcher rd =
            //  getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            RequestDispatcher rd =
              getServletContext().getRequestDispatcher(DISPLAY_REGISTRATIONS_URL);
            rd.forward(request, response);

    	}

    }
    
    private class GetDriver extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.getDriver"; //describe action in case of exception
            
            String idStr = (String)request.getParameter(ID_PARAM);
            long id = Long.parseLong(idStr);

            PersonDTO person = driverManager.getDriver(id);

            request.setAttribute(RESULT_PARAM, person);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_DRIVER_URL);
            rd.forward(request, response);
    	}

    }
    
    private class GetDriversByLastName extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.getDriver"; //describe action in case of exception
            
            String lastName = (String)request.getParameter(LAST_NAME_PARAM);
            

            List<PersonDTO> people = driverManager.getDriversByLastName(lastName);
            List<PersonDTO> results = new ArrayList<PersonDTO>();
            int index = 0;
            int count = 10;
            
            for(int i = index; i < index + count; i++) {
            	try{
            		PersonDTO newPeep = people.get(i);

                	results.add(newPeep);
            	} catch(IndexOutOfBoundsException aoe) {
            		log.debug("Reached the end of the list.");
            		break;
            	}
            }
            
            int nextIndex = (results.size()==0) ?
                    index : index + results.size();
                count = (results.size() >= count) ? count : results.size();
                //request.setAttribute(RESULT_PARAM, people);
                request.setAttribute(RESULT_PARAM, results);
                request.setAttribute(INDEX_PARAM, index);
                request.setAttribute(COUNT_PARAM, count);
                request.setAttribute(NEXT_INDEX_PARAM, nextIndex);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_DRIVERS_URL);
            rd.forward(request, response);
    	}

    }
    
    private class GetRegistrationsByOwner extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.getRegistrationsByOwner"; //describe action in case of exception
            
            String ownerId = (String)request.getParameter(OWNER_ID_PARAM);
            
            PersonDTO person = driverManager.getDriver(Integer.parseInt(ownerId));
            List<VehicleRegistrationDTO> cars = carManager.getRegistrationsByOwner(person);
            
            
            List<VehicleRegistrationDTO> results = new ArrayList<VehicleRegistrationDTO>();
            int index = 0;
            int count =  10;
            
            for(int i = index; i < index + count; i++) {
            	try{
            		VehicleRegistrationDTO newPeep = cars.get(i);

                	results.add(newPeep);
            	} catch(IndexOutOfBoundsException aoe) {
            		log.debug("Reached the end of the list.");
            		break;
            	}
            }
            int nextIndex = (results.size()==0) ?
                index : index + results.size();
            count = (results.size() >= count) ? count : results.size();
            //request.setAttribute(RESULT_PARAM, people);
            request.setAttribute(RESULT_PARAM, results);
            request.setAttribute(INDEX_PARAM, index);
            request.setAttribute(COUNT_PARAM, count);
            request.setAttribute(NEXT_INDEX_PARAM, nextIndex);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_REGISTRATIONS_URL);
            rd.forward(request, response);
    	}

    }
    
    private class GetRegistrationsByMakeModel extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.getRegistrationsByOwner"; //describe action in case of exception
            
            String make = (String)request.getParameter(MAKE_PARAM);
            String model = (String)request.getParameter(MODEL_PARAM);
            
           
            List<VehicleRegistrationDTO> cars = carManager.getRegistrationsByMakeModel(make, model);
            List<VehicleRegistrationDTO> results = new ArrayList<VehicleRegistrationDTO>();
            int index = 0;
            int count =  10;
            
            for(int i = index; i < index + count; i++) {
            	try{
            		VehicleRegistrationDTO newPeep = cars.get(i);

                	results.add(newPeep);
            	} catch(IndexOutOfBoundsException aoe) {
            		log.debug("Reached the end of the list.");
            		break;
            	}
            }
            int nextIndex = (results.size()==0) ?
                index : index + results.size();
            count = (results.size() >= count) ? count : results.size();
            //request.setAttribute(RESULT_PARAM, people);
            request.setAttribute(RESULT_PARAM, results);
            request.setAttribute(INDEX_PARAM, index);
            request.setAttribute(COUNT_PARAM, count);
            request.setAttribute(NEXT_INDEX_PARAM, nextIndex);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_REGISTRATIONS_URL);
            rd.forward(request, response);
    	}

    }
    
    private class GetRegistration extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
            action = "EJB.getDriver"; //describe action in case of exception
            
            String idStr = (String)request.getParameter(ID_PARAM);
            long id = Long.parseLong(idStr);

            VehicleRegistrationDTO car = carManager.getRegistrationById(id);

            request.setAttribute(RESULT_PARAM, car);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_REGISTRATION_URL);
            rd.forward(request, response);

    	}

    }
    
    private class PopulateDB extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.populateDB"; //describe action in case of exception
            
            testUtil.populate();

            String result = "DB Population Successful...";

            request.setAttribute(RESULT_PARAM, result);

            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            rd.forward(request, response);
    	}

    }
    
    private class ResetDB extends GetHandler {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	public void doHandle(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException,
    			Exception {
    		action = "EJB.resetDB"; //describe action in case of exception
            
            testUtil.resetAll();
            
            String result = "Reset Successful...";

            request.setAttribute(RESULT_PARAM, result);
            
            RequestDispatcher rd =
             getServletContext().getRequestDispatcher(DISPLAY_RESULT_URL);
            rd.forward(request, response);
    	}

    }
    
}
